import router from './index.js'
import { authLogin } from './../api/api.js'
import store from '@/store/store'

const redirectUrl = process.env.VUE_APP_LOGIN_REDIRECT_URL;

// 挂载路由导航守卫
router.beforeEach((to, _, next) => {
  if (to.meta.title) {
    document.title = to.meta.title;
  }
  const url = new URL(window.location.href)
  const ticket = url.searchParams.get('ticket') || store.getters['m_user/getTicket']
  const token = store.getters['m_user/getToken']
  const user = store.getters['m_user/getUser'];
  if (user && Object.keys(user).length > 0) {
    next()
    return
  }
  if (!ticket && !token) {
    window.location.href = redirectUrl
  } else {
    // 调用接口, 获取菜单
    authLogin(ticket).then((res) => {
      if (res.code === 100001) { // token过期
        window.location.href = redirectUrl
        store.commit('m_user/removeToken')
        store.commit('m_user/removeTicket')
        return
      }
      store.commit('m_user/setUser', res.data)
      localStorage.setItem('token', res.data.token)
      store.commit('m_user/setToken', res.data.token)
      store.commit('m_user/setTicket', ticket)
      store.commit('m_user/generateRoutes')
      next()
    }).catch(() => {
      next()
    })
  }
})
